//
//  AppDelegate.m
//  Unzip
//
//  Created by zhibao on 2024/1/31.
//

#import "AppDelegate.h"
#import "LNavigationViewController.h"
#import <StoreKit/StoreKit.h>
#import "TabBarController.h"
@interface AppDelegate ()<SKPaymentTransactionObserver>

@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UMConfigure initWithAppkey:@"6697d778940d5a4c49913f8f" channel:@"APP Store"];
    [MobClick setAutoPageEnabled:YES];
    
    [self creatShiLi];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    /*
     * 初始化
     */
    
    //导航
    [self setNavConfig];
    //初始化
    [self setTabbarController];
    
    [self.window makeKeyAndVisible];
    
    return YES;
}

-(void)creatShiLi{
    NSString *shiliStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"shili"];
    if (shiliStr == nil) {
        NSString *filePath1 = [[NSBundle mainBundle] pathForResource:@"示例" ofType:@"zip"];
        if (filePath1) {
            DLog(@"文件存在");
            NSString *fileName = @"示例.zip";
            [Helper saveData:@[filePath1,fileName] withDocum:IMPORTAUDIOSTYPE withType:DOCUMENTYPE];
        } else {
            DLog(@"文件不存在");
        }
        
        NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"示例" ofType:@"png"];
        if (filePath2) {
            DLog(@"文件存在");
            NSString *fileName = @"示例.png";
            [Helper saveData:@[filePath2,fileName] withDocum:IMPORTAUDIOSTYPE withType:DOCUMENTYPE];
        } else {
            
        }
        
        [[NSUserDefaults standardUserDefaults] setValue:@"shili" forKey:@"shili"];
    }
}

- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product{
    return NO;
}

- (void)setTabbarController {
    
    NSString *tempFirstStr = [[NSUserDefaults standardUserDefaults] valueForKey:WelcomeFlag];
    MYAPP.window.rootViewController = [UIViewController new];
    DLog(@"eeeee===%@",[MYGlobal share].vip_expiry);
    if ([Helper validateWithStartTime:@"2022-11-09 17:00:00" withExpireTime:@"2025-11-10 20:00:00"]) {
        [MYGlobal share].wechatFlag = 1;
    }
    
    if (tempFirstStr.length > 4) {
        TabBarController *barController = [TabBarController new];
        self.window.rootViewController = barController;
    }else{
        MYAPP.window.rootViewController = [WelcomeController new];
    }
}

- (void)setNavConfig {
    //    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    // 配置导航栏属性
    [GKConfigure setupCustomConfigure:^(GKNavigationBarConfigure *configure) {
        //       configure.gk_translationX = 15;
        //       configure.gk_translationY = 20;
        configure.backgroundColor = MyColor(@"#000000");
        configure.titleFont = MY_SCALE_RegularFONT(18);
        configure.titleColor = MyColor(@"#000000");
        //       configure.gk_scaleX = 0.90;
        configure.backImage = [UIImage imageNamed:@"arrow_back_white"];
        //       configure.gk_scaleY = 0.92;
        configure.gk_navItemLeftSpace = 12.0f;
        configure.gk_navItemRightSpace = 12.0f;
    }];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.enableAutoToolbar = YES;
}

-(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable restorableObjects))restorationHandler NS_AVAILABLE_IOS(8_0); {
    
    return YES;
}


- (void)applicationDidBecomeActive:(UIApplication *)application{
    
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
        [url startAccessingSecurityScopedResource];
        NSString *fileName = [url lastPathComponent];
        [Helper saveData:@[url,fileName] withDocum:IMPORTAUDIOSTYPE withType:DOCUMENTYPE];
        [QMUITips showSucceed: LocalizedString(@"传入成功，请前往'文件列表'查看,请下拉刷新。")];
        [url stopAccessingSecurityScopedResource];
    });
    return YES;
}


#pragma mark - 程序将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    DLog(@"程序将要进入前台");
}

- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
    
    if(transactions.count > 0){
        SKPaymentTransaction *tran = transactions.lastObject;
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                NSLog(@"交易完成");
                [self verifyPurchaseWithPaymentTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"已经购买过商品");
                break;
            case SKPaymentTransactionStateFailed:
                NSLog(@"交易失败");
                [MYGlobal share].vip_expiry = @"";
                break;
            default:
                break;
        }
    }
}
- (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction{
    //交易验证
    NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
    if(!receipt){
        return;
    }
    NSString *idkey = [DWKeychainTool getItemForKey:@"id"];
    NSString *time = [Helper getTime:TimeTypeZhou];
    if([idkey isEqualToString:@"com.jieyaya.yue"]){
        time = [Helper getTime:TimeTypeYue];
    }else if([idkey isEqualToString:@"com.jieyaya.ji"]){
        time = [Helper getTime:TimeTypeJi];
    }else if([idkey isEqualToString:@"com.jieyaya.year"]){
        time = [Helper getTime:TimeTypeNian];
    }else if([idkey isEqualToString:@"com.jieyaya.yongjiu"]){
        time = [Helper getTime:TimeTypeYongJiu];
    }
    [MobClick event:@"dingyue" attributes:@{@"type":@"xuding", @"id":transaction.payment.productIdentifier}];
    [MYGlobal share].vip_expiry = time;
}

@end
